package me.helllp.book.netty.step10;

import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.ScheduledFuture;

/**
 * 心跳消息
 * 
 * @author Administrator
 *
 */
public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter {

    private static final Log LOG = LogFactory.getLog(HeartBeatReqHandler.class);

    //	使用定时任务发送
    private volatile ScheduledFuture<?> heartBeat;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;
        
        // 	当握手成功后，Login响应向下透传，主动发送心跳消息
        if(message.getHeader() != null){
        	if(message.getHeader().getType() == MessageType.LOGIN_RESP.value()){
                //NioEventLoop是一个Schedule,因此支持定时器的执行，创建心跳计时器
                heartBeat = ctx.executor().scheduleAtFixedRate(
                        new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000,
                        TimeUnit.MILLISECONDS);
        	}else if(message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()){
                LOG.info("客户端接收到的服务端心跳消息 : ---> " + message);        		
        	}
        } else {
        	ctx.fireChannelRead(msg);
        }
    }

    //Ping消息任务类
    private class HeartBeatTask implements Runnable {
        private final ChannelHandlerContext ctx;

        public HeartBeatTask(final ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void run() {
            NettyMessage heatBeat = buildHeatBeat();
            LOG.info("客户端发送给服务端的消息 : ---> " + heatBeat);
            ctx.writeAndFlush(heatBeat);
        }

        private NettyMessage buildHeatBeat() {
            NettyMessage message = new NettyMessage();
            Header header = new Header();
            header.setType(MessageType.HEARTBEAT_REQ.value());
            message.setHeader(header);
            return message;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        if (heartBeat != null) {
            heartBeat.cancel(true);
            heartBeat = null;
        }
        ctx.fireExceptionCaught(cause);
    }
}